var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var excel = require('./excel.js')

/* 上传页面 */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
var xmlName;
/* 上传*/
router.post('/', function(req, res, next){
  //生成multiparty对象，并配置上传目标路径
  var form = new multiparty.Form({uploadDir: './public/files/'});
  //上传完成后处理
  form.parse(req, function(err, fields, files) {
    var filesTmp = JSON.stringify(files,null,2);
    
    if(err){
      console.log('parse error: ' + err);
    } else {
      var inputFile = files.inputFile[0];
      var uploadedPath = inputFile.path;
      var dstPath = './public/files/' + inputFile.originalFilename;
      // var fileName = inputFile.originalFilename;
      //console.log(dstPath);
      //重命名为真实文件名
      fs.rename(uploadedPath, dstPath, function(err) {
        if(err){
          console.log('rename error: ' + err);
        } else {
          xmlName = excel.createXml(dstPath).path;
          console.log(xmlName);
        }
      });
    }
    res.render('excel', { fn: xmlName });
    // res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
    // res.write('<a href= dstpath >Node.js</a>');
    // res.end(util.inspect({fields: fields, files: filesTmp}));
  });
});

module.exports = router;